package com.myworkbench.workbench.application.impl;

import com.myworkbench.workbench.application.SecurityAccessApplication;
import com.myworkbench.workbench.domain.common.IsDelete;
import com.myworkbench.workbench.domain.entity.role.RoleId;
import com.myworkbench.workbench.domain.entity.user.RelUserRole;
import com.myworkbench.workbench.domain.entity.user.User;
import com.myworkbench.workbench.domain.entity.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import java.util.ArrayList;
import java.util.List;

@Service
public class SecurityAccessApplicationImpl implements SecurityAccessApplication {

    private  final UserRepository userRepository;

    @Autowired
    public SecurityAccessApplicationImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    /**
     *  分页对象查询
     * @param realName
     * @param roleId
     * @return
     */
    @Override
    public Page<User> findUsersPage(String realName, RoleId roleId, PageRequest pageRequest) {
        //规格定义
        Specification<User> specification = (Specification<User>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>(); //所有的断言
            // 真实名称
            if(!StringUtils.isEmpty(realName)){
                Predicate likeRealName = cb.like(root.get("realName").as(String.class),"%"+realName+"%");
                predicates.add(likeRealName);
            }
            // 含有角色
            if(roleId !=null && roleId.getId()>0){
                // 单个角色查询
                Subquery<Long> subQuery = query.subquery(Long.class);
                Root<RelUserRole> fromUR = subQuery.from(RelUserRole.class);
                subQuery.select(fromUR.get("user").get("id")).where(cb.equal(fromUR.get("role").get("id"), roleId.getId()));
                predicates.add(cb.in(root.get("id")).value(subQuery));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        //分页信息//页码：前端从1开始，jpa从0开始，做个转换
        Pageable pageable = PageRequest.of (pageRequest.getPageNumber(),pageRequest.getPageSize());
        //查询
        return this.userRepository.findAll(specification,pageable);
    }

    @Override
    public List<User> findAllUsers() {
        return userRepository.findByIsDelete(IsDelete.YES.value());
    }


}
